package com.z_book;

import com.atguigu.book.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: SessionFilter
 * @Description:
 * @Author: wty
 * @Date: 2022/12/14
 */
@WebFilter(urlPatterns = {"*.do", "*.html"},
        initParams = {
                @WebInitParam(name = "bai", value = "/pro25/page.do?operate=page&page=user/login,/pro25/user.do?")
        })
public class SessionFilter implements Filter {
    /**
     * 白名单
     */
    private List<String> baiList;

    @Override
    public void init(FilterConfig config) throws ServletException {
        String bai = config.getInitParameter("bai");
        String[] baiArr = bai.split(",");
        baiList = Arrays.asList(baiArr);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();
        System.out.println("url = " + url);
        String queryString = request.getQueryString();
        System.out.println("queryString =" + queryString);

        String str = "";
        if (null != queryString) {
            str = url + "?" + queryString;
        } else {
            str = url + "?";
        }
        /**
         * 符合白名单的页面不用过滤
         */
        if (baiList.contains(str)) {
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession();
            User currUser = (User) session.getAttribute("currUser");

            if (null == currUser) {
                response.sendRedirect("page.do?operate=page&page=user/login");
            } else {
                // 放行
                filterChain.doFilter(request, response);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
